package com.hxh.learn.config;

import com.hxh.learn.model.SysUser;
import com.hxh.learn.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Author: hxh
 * @Date: 2023/3/1
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private LoinSuccessHandle successHandle;
    @Autowired
    private LoginFailureHandler failureHandler;

    @Autowired
    private MyAuthenticationProvider myAuthenticationProvider;
    @Autowired
    private LoginUserDetailsServiceImpl userDetailsService;
    @Autowired
    private SysUserServiceImpl sysUserService;




    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected UserDetailsService userDetailsService() {
        return username -> {
            SysUser sysUser = sysUserService.getByName(username);
            if (null == sysUser) {
                return null;
            }
            return sysUser;
        };
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用jwt不需要csrf攻击直接关闭,开启跨域 以及
        http
                //开启跨域
                .cors()
                .and()
                //关闭跨域
                .csrf()
                .disable()
                //基于token禁用session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //允许登录
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                //除了上面都需要认证
                .anyRequest()
                .authenticated()
                .and()
                //禁用缓冲
                .headers()
                .cacheControl();

    }


    /**
     * 密码加密方式否则会报错
     *
     * @return
     */
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
